var ZW_container, ZW_renderer, ZW_Scene;
var ZW_controls;    //控制器
var ZW_pickingTexture;
var ZW_needUpdate = true;
var ZW_BACK_COLOR = 0xff00ff;
var ZW_BACK_ALPHA = 1.0;
var ZW_activeCamera;      //用于渲染的相机
var ZW_normalCamera;    //常规操作的相机
var ZW_AxisHelper;
var ZW_MouseMode = 0;   //相机类型
var ZW_bBox = false;    //显示包围盒 
var ZW_FinishSceneBox;   //场景包围盒
var ZW_raycaster;   //射线碰撞检测
var ZW_Plane;   //用于检测位置的平面
var defaultLineWeight = 1;
var ZW_ColorMode = 0;   //渲染颜色模式,0和autocad一样，1为背景白色，线为黑色
var controllMode = 1; // 0  1  2 

var jsPath = document.scripts;
jsPath = jsPath[jsPath.length - 1].src.substring(0, jsPath[jsPath.length - 1].src.lastIndexOf("/") + 1);
/**
 * 本地json数据 
 */
var shapesLocalData;

/**
 * font ziti
 */
var textFont;

/**
 * 图形类型
 */
var SHAPE_TYPES = {
    // 基类（无效）
    BASE: 0,
    //直线
    LINE: 1,
    //圆
    CIRCLE: 2,
    //圆弧
    ARC: 3,
    //多段线
    POLYLINE: 4,
    //单行文字
    DBTEXT: 5,
    //块
    BLOCKREFERENCE: 6,
    //填充
    HATCH: 7,
    //多行字
    MTEXT: 8,
    //椭圆
    ELLIPSE: 9,
    //对齐标注
    ALIGNEDDIMENSION: 10,
    //转角标注
    ROTATEDDIMENSION: 11,
    //角标注
    LINEANGULARDIMENSION2: 12,
    // solid
    SOLID: 13,
    // 多引线
    MLEADER: 14,
    // 多行线
    MLINE: 15,
}

function setControllMode(index) {
    if (index == 1) {
        ZW_controls.noZoom = false;
        ZW_controls.noPan = true;
    } else if (index == 2) {
        ZW_controls.noZoom = true;
        ZW_controls.noPan = false;
    } else if (inde == 0) {
        ZW_controls.noZoom = false;
        ZW_controls.noPan = false;
    }

}

//引擎初始化
function EngineConfig(divId) {
    ZW_container = document.getElementById(divId);

    ZW_Scene = new ZW.Scene();
    var geometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });

    ZW_SceneParent = new ZW.Mesh(geometry, material);
    ZW_Scene.add(ZW_SceneParent);

    ZW_raycaster = new ZW.Raycaster();

    ZW_renderer = new ZW.WebGLRenderer({
        alpha: true,
        antialias: true,
        precision: "highp",
        preserveDrawingBuffer: true
    });
    ZW_renderer.domElement.id = 'engineId';

    ZW_renderer.setPixelRatio(window.devicePixelRatio * 1.0);
    ZW_renderer.setSize(ZW_container.offsetWidth - 4, ZW_container.offsetHeight - 4);
    ZW_renderer.setClearColor(ZW_BACK_COLOR, ZW_BACK_ALPHA);
    ZW_renderer.localClippingEnabled = true;
    ZW_container.appendChild(ZW_renderer.domElement);
    ZW_renderer.sortObjects = true;
    ZW_pickingTexture = new ZW.WebGLRenderTarget(ZW_container.offsetWidth, ZW_container.offsetHeight);
    ZW_pickingTexture.texture.minFilter = ZW.NearestFilter;

    //var frustumSize = 2000;
    //var aspect = ZW_container.offsetWidth / ZW_container.offsetHeight;
    ZW_normalCamera = new ZW.OrthographicCamera(ZW_container.offsetWidth / - 2, ZW_container.offsetWidth / 2, ZW_container.offsetHeight / 2, ZW_container.offsetHeight / - 2, 0.1, 10000);
    //ZW_normalCamera = new ZW.PerspectiveCamera(45, ZW_container.offsetWidth / ZW_container.offsetHeight, 0.000001, 100000); //常规视角相机

    ZW_activeCamera = ZW_normalCamera;
    ZW_renderer.domElement.addEventListener('mousedown', onClick0, true);
    ZW_renderer.domElement.addEventListener('mouseup', onClick, true);
    window.addEventListener('resize', onWindowResize, false);

    ZW_controls = new ZW.TrackballControls(ZW_activeCamera, ZW_renderer.domElement, new ZW.Vector3(0, 0, 0));

    var cubegeometry = new ZW.BoxBufferGeometry(100, 100, 100);
    var cubematerial = new ZW.MeshBasicMaterial({
        color: 0xff0000,
        wireframe: true
    });
    var cubemesh = new ZW.Mesh(cubegeometry, cubematerial);
    //ZW_SceneParent.add(cubemesh);

    ZW_FinishSceneBox = new ZW.Box3();
    ZW_FinishSceneBox.min.x = Infinity;
    ZW_FinishSceneBox.min.y = Infinity;
    ZW_FinishSceneBox.min.z = Infinity;
    ZW_FinishSceneBox.max.x = -Infinity;
    ZW_FinishSceneBox.max.y = -Infinity;
    ZW_FinishSceneBox.max.z = -Infinity;

    ZW_AxisHelper = new ZW.AxesHelper(200);
    // ZW_AxisHelper.position.y = 200;
    ZW_AxisHelper.name = 'axis';
    ZW_SceneParent.add(ZW_AxisHelper);

    ZW_activeCamera.position.x = 0;
    ZW_activeCamera.position.y = 0;
    ZW_activeCamera.position.z = 100;
    ZW_activeCamera.lookAt(new ZW.Vector3(0, 0, -1));

    animate();
}

function ClearScene() {
    for (var i = 0; i < ZW_SceneParent.children.length; i++) {
        var child = ZW_SceneParent.children[i];
        if (child == null)
            continue;

        if (child.name == null || child.name != 'axis') {
            ZW_SceneParent.remove(child);
            i--;
        }
    }
    ShowProcess();
}

function SetColorMode(mode) {
    ZW_ColorMode = mode;

    if (ZW_ColorMode) {
        SetBackColor(255, 255, 255, 1.0);

    } else {
        SetBackColor(53, 59, 67, 1.0);
    }
}

var ZW_cPoint = null;

function onClick0(event) {
    ZW_cPoint = event;
}

function onClick(event) {
    var disX = Math.abs(ZW_cPoint.clientX - event.clientX);
    var disY = Math.abs(ZW_cPoint.clientY - event.clientY);

    if (event.button > 0) return;    //只响应左键
    if (Math.sqrt(disX * disX + disY * disY) > 20) {  //小范围偏差认为是点击，大范围忽略掉
        return;
    }

    var clickPos = GetWorldPosByMousePos([event.pageX, event.pageY]);
    if (clickPos)
        OnMouseClick([clickPos[0], clickPos[1]]);
};

function onWindowResize() {
    ZW_renderer.setSize(ZW_container.offsetWidth, ZW_container.offsetHeight);
    ZW_pickingTexture = new ZW.WebGLRenderTarget(ZW_container.offsetWidth, ZW_container.offsetHeight);

    ShowProcess();
}

function animate() {
    requestAnimationFrame(animate);
    ZW_controls.update();
    //render();
}

function render() {
    if (ZW_needUpdate) {
        var SCREEN_WIDTH = ZW_container.offsetWidth;
        var SCREEN_HEIGHT = ZW_container.offsetHeight;

        ZW_renderer.setViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        ZW_renderer.render(ZW_Scene, ZW_activeCamera);
    }
}

//设置背景色
function SetBackColor(red, green, blue, alpha) {
    var hex = "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);

    ZW_BACK_COLOR = hex;

    if (typeof (alpha) == "undefined") {
        ZW_BACK_ALPHA = 1.0;
    } else {
        ZW_BACK_ALPHA = alpha;
    }

    ZW_renderer.setClearColor(ZW_BACK_COLOR, ZW_BACK_ALPHA);
    ShowProcess();
}

//单独渲染操作
function ShowProcess() {
    ZW_renderer.clear();
    ZW_renderer.render(ZW_Scene, ZW_activeCamera);

    OnHtmlUpdate();
}

//重置相机
function ResetViewPort() {
    var center = new ZW.Vector3();
    ZW_FinishSceneBox.getCenter(center);

    var val1 = ZW_container.offsetWidth / (ZW_FinishSceneBox.max.x - ZW_FinishSceneBox.min.x);
    var val2 = ZW_container.offsetHeight / (ZW_FinishSceneBox.max.y - ZW_FinishSceneBox.min.y);
    ZW_activeCamera.zoom = 0.8 * (val1 < val2 ? val1 : val2);
    ZW_activeCamera.position.x = center.x;
    ZW_activeCamera.position.y = center.y;
    ZW_activeCamera.position.z = 5;

    ZW_activeCamera.lookAt(new ZW.Vector3(center.x, center.y, -1));

    ZW_activeCamera.updateProjectionMatrix();

    var planeGeometry = new ZW.PlaneGeometry(10 * (ZW_FinishSceneBox.max.x - ZW_FinishSceneBox.min.x), 10 * (ZW_FinishSceneBox.max.y - ZW_FinishSceneBox.min.y));
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000,
        wireframe: true
    });
    ZW_Plane = new ZW.Mesh(planeGeometry, material);
    ZW_Plane.position.set(center.x, center.y, 0);
    //ZW_SceneParent.add(ZW_Plane);

    ShowProcess();
};

//画虚直线
function DrawDashStraightLineSegments(data, presentNode) {
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);

    var geometry = new ZW.Geometry();

    var material = new ZW.MeshBasicMaterial({
        color: 0xff9900
    });
    if (color) {
        material = new ZW.MeshBasicMaterial({
            color: color
        });
    }

    var points = [];
    var startVector = new ZW.Vector3(data.startPos[0], data.startPos[1], data.startPos[2]);
    var endVector = new ZW.Vector3(data.endPos[0], data.endPos[1], data.endPos[2]);
    points.push(startVector);
    points.push(endVector);

    var x = points[0].x - points[1].x;
    var y = points[0].y - points[1].y;
    var lineLength = Math.sqrt(x * x + y * y);  //线长
    var lineRad1 = Math.asin((points[1].x - points[0].x) / lineLength); //x弧度
    var lineRad2 = Math.asin((points[1].y - points[0].y) / lineLength); //y弧度

    var tmpDis = 0;
    var tmpPoints = [];
    tmpPoints.push(new ZW.Vector3(points[0].x, points[0].y, points[0].z));

    // console.log("data.lineTypeList.length = " + data.lineTypeList.length )
    // console.log("lineLength = " + lineLength )
    // debugger;
    while (1) {
        var isBreak = false;
        if (data.lineTypeList == null || data.lineTypeList.length == 0) {
            isBreak = true;
            break;
        }

        for (var i = 0; i < data.lineTypeList.length; i++) {
            tmpDis += Math.abs(data.lineTypeList[i].dashLength * data.lineTypeList[i].shapeScale);
            if (tmpDis > lineLength) {
                isBreak = true;
                break;
            }
            tmpPoints.push(new ZW.Vector3(points[0].x + tmpDis * Math.sin(lineRad1), points[0].y + tmpDis * Math.sin(lineRad2), points[0].z));
        }

        if (isBreak)
            break;
    }

    tmpPoints.push(new ZW.Vector3(points[1].x, points[1].y, points[1].z));

    var startPointPer = {};
    for (var i = 0; i < tmpPoints.length; i++) {
        if (i == 0) {
            startPointPer = tmpPoints[0];
            continue;
        } else {
            var endPointPer = tmpPoints[i];

            var dashSum = 0;
            dashSum = data.lineTypeList == null ? 0 : data.lineTypeList.length;
            var tempDashlen = 1;
            if (dashSum != 0) {
                var tempIndex = i % dashSum == 0 ? dashSum - 1 : i % dashSum - 1;
                tempDashlen = data.lineTypeList[tempIndex].dashLength;
            }

            if (tempDashlen > 0) {
                var pts = [];
                var lineWeight = defaultLineWeight;
                if (data.startWidth != null)
                    lineWeight = data.startWidth + defaultLineWeight;

                var randomPoints = [];
                randomPoints.push(startPointPer);
                randomPoints.push(endPointPer);
                var randomSpline = new ZW.CatmullRomCurve3(randomPoints);

                var extrudeSettings = {
                    steps: randomPoints.length,
                    bevelEnabled: false,
                    extrudePath: randomSpline
                };

                pts.push(new ZW.Vector2(0, 0));
                pts.push(new ZW.Vector2(lineWeight, 0));
                pts.push(new ZW.Vector2(lineWeight, lineWeight));
                pts.push(new ZW.Vector2(0, lineWeight));

                var shape = new ZW.Shape(pts);
                var geometry = new ZW.ExtrudeBufferGeometry(shape, extrudeSettings);
                var mesh = new ZW.Mesh(geometry, material);
                presentNode.add(mesh);
            } else {
                var lineData = {};
                lineData.startPos = [];
                lineData.endPos = [];
                lineData.startPos[0] = startPointPer.x;
                lineData.startPos[1] = startPointPer.y;
                lineData.startPos[2] = startPointPer.z;
                lineData.endPos[0] = endPointPer.x;
                lineData.endPos[1] = endPointPer.y;
                lineData.endPos[2] = endPointPer.z;

                lineData.color = data.color;
                drawLineSegment(lineData, presentNode);
            }

        }
    }
    startPointPer = tmpPoints[i];
}


/**
 * 读取CAD图元json文件
 */
function AddDrawing(jsonPath, bJson) {
    //如果没预先加载字体，先加载字体后再加载json数据
    var fontName = 'PGothic_Regular.json';  //'STCFS_Regular.json'为中文,'PGothic_Regular'为日文
    if (!textFont) {
        var loader = new ZW.FontLoader();
        loader.load(jsPath + fontName, function (font) {
            textFont = font;
            $(document).ready(function () {
                if (bJson) {
                    $.ajax({
                        url: jsonPath,
                        async: false,
                        xhrFields: {
                            withCredentials: true    // 前端设置是否带cookie
                        },
                        crossDomain: true,   // 会让请求头中包含跨域的额外信息，但不会含cookie
                        success: function (data) {
                            genInitData(data);
                        }
                    });
                } else {
                    JSZipUtils.getBinaryContent(jsonPath, function (err, data) {
                        JSZip.loadAsync(data).then(function (zip) {
                            var dirIndex = jsonPath.lastIndexOf("/");
                            var index = jsonPath.lastIndexOf(".");
                            var myname = (jsonPath.substr(dirIndex + 1, index - dirIndex - 1));
                            zip.file(myname + '.json').async("text").then(function (text1) {
                                genInitData(text1);
                            })
                        })
                    });
                }
            });
        });
    } else {
        if (bJson) {
            $(document).ready(function () {
                $.ajax({
                    url: jsonPath,
                    async: false,
                    success: function (data) {
                        genInitData(data);
                    }
                });
            });
        } else {
            JSZipUtils.getBinaryContent(jsonPath, function (err, data) {
                JSZip.loadAsync(data).then(function (zip) {
                    var dirIndex = jsonPath.lastIndexOf("/");
                    var index = jsonPath.lastIndexOf(".");
                    var myname = (jsonPath.substr(dirIndex + 1, index - dirIndex - 1));
                    zip.file(myname + '.json').async("text").then(function (text1) {
                        genInitData(text1);
                    })
                })
            });
        }

    }

    var genInitData = function (in_data) {
        var tempData = JSON.parse(in_data);
        ZW_FinishSceneBox.max.x = tempData.bound[0];
        ZW_FinishSceneBox.max.y = tempData.bound[1];
        ZW_FinishSceneBox.max.z = 0.01;
        ZW_FinishSceneBox.min.x = tempData.bound[2];
        ZW_FinishSceneBox.min.y = tempData.bound[3];
        ZW_FinishSceneBox.min.z = 0;

        if (ZW_bBox) {
            var helper1 = new ZW.Box3Helper(ZW_FinishSceneBox, 0xff0000);
            ZW_SceneParent.add(helper1);
        }

        //console.log(data.length);
        shapesLocalData = tempData.content;
        genDefaultLineWeight();

        if (ZW_ColorMode == 1) {  //a-mis的cad风格
            for (var i = 0; i < shapesLocalData.length; i++) {
                if (shapesLocalData[i].color && (shapesLocalData[i].color[0] + shapesLocalData[i].color[1] + shapesLocalData[i].color[1]) > 764) {
                    shapesLocalData[i].color[0] = 0;
                    shapesLocalData[i].color[1] = 0;
                    shapesLocalData[i].color[2] = 0;
                }
                //console.log(shapesLocalData[i]);
            }
        }
        resolveLocalData(shapesLocalData, ZW_SceneParent);
        ResetViewPort();

        OnDrawingLoaded();
    }
}

function genDefaultLineWeight() {
    var gapX = ZW_FinishSceneBox.max.x - ZW_FinishSceneBox.min.x;
    var gapY = ZW_FinishSceneBox.max.y - ZW_FinishSceneBox.min.y;
    var gapMax = Math.min(gapX, gapY);
    defaultLineWeight = gapMax / 2000;
}

function resolveLocalData(inData, parentNode) {
    // console.log("inData-length:" + inData.length);
    if (inData == null || inData.length == 0) {
        // alert("本地json异常");
        return;
    }

    for (var i = 0; i < inData.length; i++) {
        var tempData = inData[i];
        if (tempData == null) {
            continue;
        }

        if (ZW_ColorMode == 1) {  //a-mis的cad风格
            if (tempData.color && (tempData.color[0] + tempData.color[1] + tempData.color[1]) > 764) {
                tempData.color[0] = 0;
                tempData.color[1] = 0;
                tempData.color[2] = 0;
            }
        }

        if (ZW_bBox && tempData.bound) {
            var tmpBox = new ZW.Box3();
            tmpBox.max.x = tempData.bound[0];
            tmpBox.max.y = tempData.bound[1];
            tmpBox.max.z = 0.01;
            tmpBox.min.x = tempData.bound[2];
            tmpBox.min.y = tempData.bound[3];
            tmpBox.min.z = 0;

            var helper1 = new ZW.Box3Helper(tmpBox, 0xff0000);
            parentNode.add(helper1);
        }

        switch (tempData.shapeType) {
            case SHAPE_TYPES.BASE:
                break;
            case SHAPE_TYPES.LINE:
                // drawLineSegment(tempData, parentNode);
                DrawDashStraightLineSegments(tempData, parentNode);
                break;
            case SHAPE_TYPES.CIRCLE:
                drawCircle(tempData, parentNode);
                break;
            case SHAPE_TYPES.ARC:
                drawArc(tempData, parentNode);
                break;
            case SHAPE_TYPES.POLYLINE:
                drawPolyLine(tempData, parentNode);
                break;
            case SHAPE_TYPES.DBTEXT:
                drawDBText(tempData, parentNode);
                break;
            case SHAPE_TYPES.BLOCKREFERENCE:
                drawBLockReference(tempData, parentNode);
                break;
            case SHAPE_TYPES.MTEXT:
                drawMText(tempData, parentNode);
                break;
            case SHAPE_TYPES.ELLIPSE:
                drawEllipse(tempData, parentNode);
                break;
            case SHAPE_TYPES.ALIGNEDDIMENSION:
                drawAlignedDimension(tempData, parentNode);
                break;
            case SHAPE_TYPES.ROTATEDDIMENSION:
                drawRotatedDimension(tempData, parentNode);
                break;
            case SHAPE_TYPES.LINEANGULARDIMENSION2:
                drawLineAngularDimension(tempData, parentNode);
                break;
            case SHAPE_TYPES.HATCH:
                drawHatch(tempData, ZW_SceneParent);
                break;
            case SHAPE_TYPES.SOLID:
                drawSolid(tempData, ZW_SceneParent);
                break;
            case SHAPE_TYPES.MLEADER:
                drawMleader(tempData, ZW_SceneParent);
                break;
            case SHAPE_TYPES.MLINE:
                drawMline(tempData, ZW_SceneParent);
                break;
        }
    }
}

/**
 * draw  line by points
 * @param {*} data 
 */
function drawLineSegment(data, presentNode) {
    var geometry = new ZW.Geometry();

    // 起止点
    var startVector = new ZW.Vector3(data.startPos[0], data.startPos[1], data.startPos[2]);
    var endVector = new ZW.Vector3(data.endPos[0], data.endPos[1], data.endPos[2]);
    geometry.vertices.push(startVector);
    geometry.vertices.push(endVector);

    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    // var color = sRgb.colorHex();

    var color = colorHex(sRgb);
    var material = new ZW.LineBasicMaterial({
        color: color //线条颜色
    });

    var line = new ZW.Line(geometry, material);
    presentNode.add(line);
}

/**
 * draw ellipse 椭圆
 * @param {*} data 
 */
function drawEllipse(data, presentNode) {
    var geometry = new ZW.Geometry();

    var center = new ZW.Vector3(data.center[0], data.center[1], data.center[2]);
    var radius = data.radius;
    var segments = 48;
    var startAngle = data.startAngle;
    var endAngle = data.endAngle;

    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);
    var material = new ZW.LineBasicMaterial({
        color: color //线条颜色
    });

    var ellipse = new ZW.EllipseCurve(center[0], center[1],
        data.majorRadius, data.minorRadius, startAngle, endAngle, false, 0);

    var ellipsePath = new ZW.CurvePath();
    ellipsePath.add(ellipse);
    var ellipseGeometry = ellipsePath.createPointsGeometry(200);
    ellipseGeometry.computeTangents();
    line = new ZW.Line(ellipseGeometry, material);
    line.position.x = data.center[0];
    line.position.y = data.center[1];
    line.position.z = data.center[2];

    var _a = new ZW.Vector3(data.majorAxis[0], data.majorAxis[1], data.majorAxis[2]);
    var _b = new ZW.Vector3(1, 0, 0);
    var angle = _a.angleTo(_b)
    var _c = ZW.Math.radToDeg(angle);
    line.rotateZ(0 - angle); //x轴旋转90度

    presentNode.add(line);

}

/**
 * draw circle
 * @param {*} data 
 */
function drawCircle(data, presentNode) {
    var geometry = new ZW.Geometry();

    var center = new ZW.Vector3(data.center[0], data.center[1], data.center[2]);
    var radius = data.radius;
    var segments = 48;

    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);
    var material = new ZW.LineBasicMaterial({
        color: color //线条颜色
    });

    geometry = new ZW.CircleGeometry(radius, segments);
    // Remove center vertex
    geometry.vertices.shift();

    var circle = new ZW.LineLoop(geometry, material);
    circle.position.x = data.center[0];
    circle.position.y = data.center[1];
    circle.position.z = data.center[2];

    presentNode.add(circle);
}

/**
 * 
 */
function drawArc(data, presentNode) {
    var geometry = new ZW.Geometry();

    var center = new ZW.Vector3(data.center[0], data.center[1], data.center[2]);
    var radius = data.radius;
    var segments = 48;
    var startAngle = data.startAngle;
    var endAngle = data.endAngle;
    var totalAngle = data.totalAngle;

    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);
    var material = new ZW.LineBasicMaterial({
        color: color //线条颜色
    });

    geometry = new ZW.CircleGeometry(radius, segments, startAngle, totalAngle);
    // Remove center vertex
    geometry.vertices.shift();

    var circle = new ZW.Line(geometry, material);
    circle.position.x = data.center[0];
    circle.position.y = data.center[1];
    circle.position.z = data.center[2];

    presentNode.add(circle);
}

/* 暂未完成
function drawArc(data, presentNode) {
    var geometry = new ZW.Geometry();

    var center = new ZW.Vector3(data.center[0], data.center[1], data.center[2]);
    var radius = data.radius;
    var segments = 48;
    var startAngle = data.startAngle;
    var endAngle = data.endAngle;
    var totalAngle = data.totalAngle;

    var lineWeight = data.startWidth + defaultLineWeight;

    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);
    var material = new ZW.MeshBasicMaterial({
        color: color //线条颜色
    });

    if (totalAngle < 0) {
        startAngle += totalAngle;
        totalAngle = Math.abs(totalAngle);
    }

    var circle = new ZW.Mesh(new ZW.RingBufferGeometry(radius - lineWeight / 2, radius + lineWeight / 2,
        segments, 5, startAngle, totalAngle), material);
    circle.position.x = data.center[0];
    circle.position.y = data.center[1];
    circle.position.z = data.center[2];
    presentNode.add(circle);
}
*/

function drawPolyLine(data, presentNode) {
    // var geometry = new ZW.Geometry();

    // var closed = data.closed;

    // for (var i = 0; i < data.vertices.length; i++) {
    //     var tempVector = new ZW.Vector3(data.vertices[i].point[0], data.vertices[i].point[1], data.vertices[i].point[2]);
    //     geometry.vertices.push(tempVector);
    // }

    // // 颜色
    // var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    // var color = colorHex(sRgb);
    // var material = new ZW.LineBasicMaterial({
    //     color: color //线条颜色
    // });

    // var line = closed ? new ZW.LineLoop(geometry, material) : new ZW.Line(geometry, material);
    // presentNode.add(line);


    var subGeometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });

    var subNode = new ZW.Mesh(subGeometry, material);
    presentNode.add(subNode);

    for (var i = 0; i < data.vertices.length; i++) {

        var itemData = data.vertices[i];
        itemData.color = data.color;
        // itemData.startAngle = itemData.startAngle - 10 * Math.PI / 180;
        // itemData.endAngle = itemData.endAngle - 10 * Math.PI / 180;

        if (itemData.segmentType == 1) {
            var originVectorAngle = 0;
            var axisX = new ZW.Vector3(1, 0, 0);

            // 起点、中点 向量
            var startVector = new ZW.Vector3(itemData.startPoint[0] - itemData.center[0],
                itemData.startPoint[1] - itemData.center[1], itemData.startPoint[2] - itemData.center[2]);

            // 终点、中点 向量
            var endVector = new ZW.Vector3(itemData.endPoint[0] - itemData.center[0],
                itemData.endPoint[1] - itemData.center[1], itemData.endPoint[2] - itemData.center[2]);

            /**
             * 
             * @param {*} tarVector 
             * @param {*} vectorBase  从tarVector到vectorBase 
             */
            var vectorsAngleToX = (tar) => {
                let x = new ZW.Vector3(1, 0, 0);
                var angle = tar.angleTo(x);

                var re = angle; //  + (Math.PI / 180 * 0)
                if (tar.x >= 0 && tar.y >= 0) {

                } else if (tar.x <= 0 && tar.y >= 0) {

                } else if (tar.x <= 0 && tar.y <= 0) {
                    re = 2 * Math.PI - angle;
                } else if (tar.x >= 0 && tar.y <= 0) {
                    re = 2 * Math.PI - angle;
                }
                return re;
            }

            itemData.startAngle = vectorsAngleToX(startVector);
            // itemData.endAngle = vectorsAngleToX(endVector);
            // itemData.totalAngle = itemData.isClockWise ? 0 - Math.abs(itemData.startAngle - itemData.endAngle) :
            //     Math.abs(itemData.startAngle - itemData.endAngle);
            // itemData.totalAngle = itemData.endAngle - itemData.startAngle;

            if (!itemData.isClockWise)
                // if(1)
                itemData.totalAngle = Math.abs(itemData.endAngle);
            else
                itemData.totalAngle = 0 - Math.abs(itemData.endAngle);

            drawArc(itemData, subNode);
        }
        else if (itemData.segmentType == 0) {
            itemData.startPos = itemData.startPoint;
            itemData.endPos = itemData.endPoint;
            itemData.color = data.color;
            itemData.lineTypeList = data.lineTypeList;

            DrawDashStraightLineSegments(itemData, subNode);
        }
    }

}

function drawDBText(data, presentNode) {
    //添加文字
    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);

    var matLite = new ZW.MeshBasicMaterial({
        color: color,
        transparent: true,
        side: ZW.DoubleSide
    });

    var group = new ZW.Group();
    presentNode.add(group);
    // 位置
    group.position.set(data.position[0], data.position[1], data.position[2]);
    // rotation
    group.rotateZ(data.rotation); //x轴旋转90度

    // 字符串替换及分组
    var placedStr = replaceSpecialCharacter(data.textString);
    var splitedStrs = splitBySpecialCharacter(placedStr);

    // 分组子串加载
    var startPos = [0, 0, 0];
    for (var i = 0; i < splitedStrs.length; i++) {
        var shapes = textFont.generateShapes(splitedStrs[i].str, data.height);
        var geometry = new ZW.ShapeBufferGeometry(shapes);
        geometry.computeBoundingBox();

        // 偏移？  需要在标注中验证是否依然有效
        var hPos = 0, vPos = 0;
        if (data.horizontalPlacement == "center")
            hPos = 0.5 * (geometry.boundingBox.max.x - geometry.boundingBox.min.x);
        geometry.translate(-hPos, vPos, 0);

        // widthFactor
        var text = new ZW.Mesh(geometry, matLite);
        text.scale.set(1 * data.widthFactor, 1, 1);

        // position  局部位置
        text.position.set(startPos[0], startPos[1], startPos[2]);

        text.name = 'word';
        group.add(text);

        // 上下线计算
        var deltaHeight = defaultLineWeight * 10;
        var downStart = [startPos[0], startPos[1] - deltaHeight, startPos[2]]
        var downEnd = [startPos[0] + (geometry.boundingBox.max.x - geometry.boundingBox.min.x), startPos[1] - deltaHeight, startPos[2]]

        var upStart = [startPos[0], startPos[1] + (geometry.boundingBox.max.y - geometry.boundingBox.min.y) + deltaHeight, startPos[2]]
        var upEnd = [startPos[0] + (geometry.boundingBox.max.x - geometry.boundingBox.min.x),
        startPos[1] + (geometry.boundingBox.max.y - geometry.boundingBox.min.y) + deltaHeight, startPos[2]]

        if (splitedStrs[i].state == 2 || splitedStrs[i].state == 3) {
            var upLineData = {};
            upLineData.startPos = downStart;
            upLineData.endPos = downEnd;
            upLineData.shapeType = 1;
            upLineData.color = data.color;
            upLineData.lineWeight = 211;
            DrawDashStraightLineSegments(upLineData, group);
        }
        if (splitedStrs[i].state == 1 || splitedStrs[i].state == 3) {
            var downLineData = {};
            downLineData.startPos = upStart;
            downLineData.endPos = upEnd;
            downLineData.shapeType = 1;
            downLineData.color = data.color;
            downLineData.lineWeight = 211;
            DrawDashStraightLineSegments(downLineData, group);
        }

        startPos[0] = startPos[0] + (geometry.boundingBox.max.x - geometry.boundingBox.min.x);
    }
}

var replaceSpecialCharacter = function (in_str) {
    // string.replace(new RegExp(key,'g'),"b");
    var re = in_str;
    for (var i = 0; i < SpecialReplaceCharacters.length; i++) {
        var tempSc = SpecialReplaceCharacters[i];
        if (re.includes(tempSc.OriginChars))
            re = re.replace(new RegExp(tempSc.OriginChars, 'g'), tempSc.ReplaceChars);
    }
    return re;
};

var splitBySpecialCharacter = function (in_str) {
    var upLinePos = [], downLinePos = [];
    var curState = 0; // 0 无状态 1 上  2  下 3 上下

    var charsList = [];
    while (1) {
        var timePos = -1; var timeState = ''; var timeChars = '';
        for (var i = 0; i < SpecialLineCharacters.length; i++) {
            var tempPos0 = in_str.indexOf(SpecialLineCharacters[i].OriginChars);

            if (tempPos0 >= 0) {
                if (timePos < 0) { // 首次出现特殊字符串 位置赋值 状态赋值
                    timePos = tempPos0;
                    timeChars = SpecialLineCharacters[i].OriginChars;
                    timeState = SpecialLineCharacters[i].LineChars;
                } else if (timePos > 0 && tempPos0 < timePos) { // 出现比记录的特殊字符串位置靠前 位置赋值 状态赋值
                    timePos = tempPos0;
                    timeChars = SpecialLineCharacters[i].OriginChars;
                    timeState = SpecialLineCharacters[i].LineChars;
                } else if (timePos > 0 && tempPos0 == timePos) {// 与记录的特殊字符串位置一致
                    timePos = tempPos0; // 位置赋值
                    timeChars = SpecialLineCharacters[i].OriginChars;
                    var tempState = SpecialLineCharacters[i].LineChars;
                    // 有状态记录  且不一致  增加到上下状态
                    if ((timeState == 1 || timeState == 2) && tempState != timeState) {
                        timeState = 3;
                    }
                    // 有状态记录  且一致 转为普通状态
                    else if (tempState == timeState) {
                        timeState = 0;
                    }
                    // 无状态记录 
                    else if (timeState == 0) {
                        timeState = tempState;
                    }
                } else if (timePos == 0) {
                    if (timePos == tempPos0) {
                        timeChars = SpecialLineCharacters[i].OriginChars;
                        timeState = 3;
                    }
                }
            }
        }

        if (timePos > 0) {
            var tempStr = in_str.substring(0, timePos);
            var charsItem = {};
            charsItem.str = tempStr;
            charsItem.state = curState;
            charsList.push(charsItem);
        } else if (timePos == 0) {
        }
        else {
            var charsItem = {};
            charsItem.str = in_str;
            charsItem.state = curState;
            charsList.push(charsItem);
            break;
        }

        in_str = in_str.substring(timePos + timeChars.length, in_str.length);

        if ((curState == 1 && timeState == 2) || (curState == 2 && timeState == 1))
            curState = 3;
        else if (curState == 3 && (timeState == 1 || timeState == 2))
            curState = 3 - timeState;
        else if (curState == timeState)
            curState = 0;
        else if (curState == 0)
            curState = timeState;

        if (timePos == -1)
            break;
    }

    console.log(charsList);
    return charsList;
};

function drawMText(data, presentNode) {
    /**
     * 字符串内插入字符
     * @param {*} soure 原始字符串
     * @param {*} start 插入位置
     * @param {*} newStr 插入的字符串
     */
    let insertStr = (soure, start, newStr) => {
        return soure.slice(0, start) + newStr + soure.slice(start)
    }

    /**
     * 计算单个文字宽度
     * @param {*} in_descent 
     * @param {*} in_ascent 
     * @param {*} font_height 
     * @param {*} font_width_degree 
     * @param {*} line_height 
     */
    let conutFontWidth = (in_descent, in_ascent, font_height, font_width_degree, line_height) => {
        var re = 1.0;
        re = font_height / 0.65;
        re = re * font_width_degree;
        return re;
    }

    /**
     * 计算偏移位置量 对齐方式？
     * @param {*} in_descent 
     * @param {*} in_ascent 
     * @param {*} font_height 
     * @param {*} font_width_degree 
     * @param {*} line_height 
     */
    let countTextPositonOffset = (in_descent, in_ascent, font_height, font_width_degree, line_height) => {
        var re = [0, 0];
        re[0] = 0;
        re[1] = conutFontWidth(data.descent, data.ascent, data.textHeight, 1.0, data.lineHeight);
        return re;
    }

    var signalTextWidth = conutFontWidth(data.descent, data.ascent, data.textHeight, 1.0, data.lineHeight);
    var lineWidth = 0;
    // var tempStr = data.textString;
    var tempStr = replaceSpecialCharacter(data.textString);

    for (var i = 0; i < tempStr.length; i++) {
        if (i > 1000)
            break;
        if (tempStr[i].match(/[^\x00-\xff]/ig) != null)
            lineWidth += signalTextWidth;
        else
            lineWidth += signalTextWidth / 2;

        if (lineWidth > data.width) {
            lineWidth = 0;
            tempStr = insertStr(tempStr, i, '\n')
            i++;
        }
    }
    data.textString = tempStr;

    //添加文字
    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);

    var matLite = new ZW.MeshBasicMaterial({
        color: color,
        transparent: true,
        side: ZW.DoubleSide
    });

    // 文字 textString  高度  height
    var text = data.textString;
    var shapes = textFont.generateShapes(text, data.textHeight);

    var geometry = new ZW.ShapeBufferGeometry(shapes);
    geometry.computeBoundingBox();

    // 位移
    // var xMid = - 0.5 * (geometry.boundingBox.max.x - geometry.boundingBox.min.x);
    // geometry.translate(0, 0, 0);

    // widthFactor
    var textMesh = new ZW.Mesh(geometry, matLite);
    // textMesh.scale.set(1 * data.widthFactor, 1, 1);

    // rotation
    // text.rotateZ(Math.PI / 180 * data.rotation); //x轴旋转90度
    textMesh.rotateZ(data.rotation); //x轴旋转90度

    // position  位置
    var positionOffset = countTextPositonOffset(data.descent, data.ascent, data.textHeight, 1.0, data.lineHeight);
    textMesh.position.set(data.position[0], data.position[1] - positionOffset[1], data.position[2]);
    textMesh.name = 'word';
    presentNode.add(textMesh);
}

/**
 * 块引用
 * @param {*} data 
 */
function drawBLockReference(data, presentNode) {
    var subGeometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });

    var subNode = new ZW.Mesh(subGeometry, material);
    presentNode.add(subNode);

    resolveLocalData(data.mSubEntities, subNode);
}

/**
 * 对齐标注
 * @param {*} data 
 * @param {*} presentNode 
 */
function drawAlignedDimension(data, presentNode) {
    /**
     * 计算直线的法向量
     * @param {*} point1 直线端点1
     * @param {*} point1 直线端点2
     */
    var lineNormal = (point1, point2) => {
        var nx = point2.y - point1.y,
            ny = point1.x - point2.x;
        var normalLine = { x: nx, y: ny };
        return normalLine;
    }

    /**
     * 点到线的交点
     * @param {*} linePoint1 
     * @param {*} linePoint2 
     * @param {*} point 
     */
    var intersectionByPointToLine = (linePoint1, linePoint2, point) => {
        var P = {};
        //如果p1.x==p2.x 说明是条竖着的线
        if (linePoint1.x - linePoint2.x == 0) {
            P.x = linePoint1.x;
            P.y = point.y;
        }
        else {
            var A = (linePoint1.y - linePoint2.y) / (linePoint1.x - linePoint2.x)
            var B = linePoint1.y - A * linePoint1.x
            var m = point.x + A * point.y

            P.x = (m - A * B) / (A * A + 1)
            P.y = A * P.x + B
        }
        return P
    }

    /**
     * 点到线的距离
     * @param {*} linePoint1 
     * @param {*} linePoint2 
     * @param {*} point 
     */
    var distanceByPointToLine = (linePoint1, linePoint2, point) => {
        var len;

        //如果p1.x==p2.x 说明是条竖着的线
        if (linePoint1.x - linePoint2.x == 0) {
            len = Math.abs(point.x - linePoint1.x)
        }
        else {
            var A = (linePoint1.y - linePoint2.y) / (linePoint1.x - linePoint2.x)
            var B = linePoint1.y - A * linePoint1.x

            len = Math.abs((A * point.x + B - point.y) / Math.sqrt(A * A + 1))
        }

        return len
    }

    /**
     * point 在方向上移动
     * @param {*} vectorIn 
     * @param {*} point 
     */
    var movePointByVector = (vectorIn, point, distance) => {
        var vectorMagnitude = Math.sqrt(Math.pow(vectorIn.x, 2) + Math.pow(vectorIn.y, 2))

        var unitVector = {};
        unitVector.x = vectorIn.x / vectorMagnitude;
        unitVector.y = vectorIn.y / vectorMagnitude;

        var re = { x: point.x + (unitVector.x * distance), y: point.y + (unitVector.y * distance) };

        return re;
    }

    var genArrowShape = (dimBlkName, dimBlkData, arrowsNode, arrowsColor) => {
        if (dimBlkName != 'default') {
            resolveLocalData(dimBlkData, arrowsNode);
        } else {
            $(document).ready(function () {
                $.ajax({
                    url: '../default-arrow-shape.json',
                    async: true,
                    success: function (data) {
                        var arrowData = JSON.parse(data);
                        for (let i = 0; i < arrowData.length; i++) {
                            arrowData[i].color = arrowsColor;
                        }
                        resolveLocalData(arrowData, arrowsNode);
                    }
                });
            });
        }
        return arrowsNode;
    }

    var line1Point = { x: data.xLine1Point[0], y: data.xLine1Point[1] };
    var line2Point = { x: data.xLine2Point[0], y: data.xLine2Point[1] };
    var txtPosition = { x: data.textPosition[0], y: data.textPosition[1] };

    // 标注线的法向量
    //    var p2pNormal = lineNormal(line1Point, line2Point);
    var pointInLine = intersectionByPointToLine(line1Point, line2Point, txtPosition);
    var p2pNormal = { x: txtPosition.x - pointInLine.x, y: txtPosition.y - pointInLine.y };

    // pointToLineGap
    var pointToLineGap = distanceByPointToLine(line1Point, line2Point, txtPosition);

    // 标尺线两端点
    var line1PointMoved = movePointByVector(p2pNormal, line1Point, pointToLineGap);
    var line2PointMoved = movePointByVector(p2pNormal, line2Point, pointToLineGap);

    // 边界线 端点 edgeLinePoint1
    var edgeLine1Point1 = movePointByVector(p2pNormal, line1Point, data.dimExo);
    var edgeLine2Point1 = movePointByVector(p2pNormal, line2Point, data.dimExo);

    // 边界线 端点 edgeLinePoint2
    var edgeLine1Point2 = movePointByVector(p2pNormal, line1PointMoved, data.dimExe);
    var edgeLine2Point2 = movePointByVector(p2pNormal, line2PointMoved, data.dimExe);

    var subGeometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });

    var subNode = new ZW.Mesh(subGeometry, material);
    presentNode.add(subNode);

    // 尺寸线
    var signLineData = {};
    signLineData.startPos = [line1PointMoved.x, line1PointMoved.y, 0];
    signLineData.endPos = [line2PointMoved.x, line2PointMoved.y, 0];
    signLineData.color = data.dimClrd;
    DrawDashStraightLineSegments(signLineData, subNode);

    // 边界线
    var edgeLineData1 = {};
    edgeLineData1.startPos = [edgeLine1Point1.x, edgeLine1Point1.y, 0];
    edgeLineData1.endPos = [edgeLine1Point2.x, edgeLine1Point2.y, 0];
    edgeLineData1.color = data.dimClre;
    DrawDashStraightLineSegments(edgeLineData1, subNode);

    // 边界线
    var edgeLineData2 = {};
    edgeLineData2.startPos = [edgeLine2Point1.x, edgeLine2Point1.y, 0];
    edgeLineData2.endPos = [edgeLine2Point2.x, edgeLine2Point2.y, 0];
    edgeLineData2.color = data.dimClre;
    DrawDashStraightLineSegments(edgeLineData2, subNode);

    // 文字
    var textData = {};
    textData.textString = data.prefix + parseFloat(data.measurement).toFixed(data.dimDec) + data.suffix;
    textData.height = data.dimTxt;

    var _a = new ZW.Vector3(line1Point.x - line2Point.x, line1Point.y - line2Point.y, line1Point.z - line2Point.z);
    _b = new ZW.Vector3(1, 0, 0);

    var tempRotation = _b.angleTo(_a);
    var resRotate = tempRotation;
    if (_a.x < 0 && _a.y < 0)
        resRotate = Math.PI - tempRotation;
    else if (_a.x < 0 && _a.y > 0)
        resRotate = 0 - (Math.PI - tempRotation);
    else if (_a.x > 0 && _a.y < 0)
        resRotate = -tempRotation;

    textData.rotation = resRotate;
    textData.position = data.textPosition;
    textData.color = data.dimClrt;
    textData.widthFactor = 1;
    textData.horizontalPlacement = "center";

    drawDBText(textData, subNode);

    // 箭头
    var subArrowsNode1 = new ZW.Mesh(subGeometry, material);
    subNode.add(subArrowsNode1);
    var subArrowsNode2 = new ZW.Mesh(subGeometry, material);
    subNode.add(subArrowsNode2);

    if (data.dimSah) {
        genArrowShape(data.dimBlk1Name, data.dimBlk1Shapes, subArrowsNode1, data.dimClrd);
        genArrowShape(data.dimBlk2Name, data.dimBlk2Shapes, subArrowsNode2, data.dimClrd);
    } else {
        genArrowShape(data.dimBlkName, data.dimBlkShapes, subArrowsNode1, data.dimClrd);
        genArrowShape(data.dimBlkName, data.dimBlkShapes, subArrowsNode2, data.dimClrd);
    }

    subArrowsNode1.scale.set(1 * data.dimaSz, 1 * data.dimaSz, 1 * data.dimaSz);
    subArrowsNode2.scale.set(1 * data.dimaSz, 1 * data.dimaSz, 1 * data.dimaSz);
    subArrowsNode1.position.set(line1PointMoved.x, line1PointMoved.y, 0);
    subArrowsNode2.position.set(line2PointMoved.x, line2PointMoved.y, 0);


    var tempArrowRotation = _b.angleTo(_a);
    var resArrowRotate = tempArrowRotation;
    if (_a.x < 0 && _a.y < 0)
        resArrowRotate = 0 - tempArrowRotation;
    else if (_a.x > 0 && _a.y > 0)
        resArrowRotate = tempArrowRotation;
    // else if (_a.x < 0 && _a.y > 0)
    //     resArrowRotate = 0 - (Math.PI - tempArrowRotation);
    else if (_a.x > 0 && _a.y < 0)
        resArrowRotate = 0 - tempArrowRotation;

    subArrowsNode1.rotateZ(resArrowRotate);
    subArrowsNode2.rotateZ(Math.PI + resArrowRotate);
}

/**
 * 转角标注
 * @param {*} data 
 * @param {*} presentNode 
 */
function drawRotatedDimension(data, presentNode) {
    /**
     * 计算直线的法向量
     * @param {*} point1 直线端点1
     * @param {*} point2 直线端点2
     */
    var lineNormal = (point1, point2) => {
        var nx = point2.y - point1.y,
            ny = point1.x - point2.x;
        var normalLine = { x: nx, y: ny };
        return normalLine;
    }

    /**
     * 计算标注线端点
     */
    var measurementLinePoint = (linePoint, rotation, txtPosition) => {
        var re = { x: 0, y: 0 };
        if (rotation == 0) {
            re = { x: linePoint.x, y: txtPosition.y };
        } else if (rotation > 0) {
            re = { x: txtPosition.x, y: linePoint.y };
        }

        return re;
    }

    var genArrowShape = (dimBlkName, dimBlkData, arrowsNode, arrowsColor) => {
        if (dimBlkName != 'default') {
            resolveLocalData(dimBlkData, arrowsNode);
        } else {
            $(document).ready(function () {
                $.ajax({
                    url: '../default-arrow-shape.json',
                    async: true,
                    success: function (data) {
                        var arrowData = JSON.parse(data);
                        for (let i = 0; i < arrowData.length; i++) {
                            arrowData[i].color = arrowsColor;
                        }
                        resolveLocalData(arrowData, arrowsNode);
                    }
                });
            });
        }
        return arrowsNode;
    }

    /**
     * point 在方向上移动
     * @param {*} vectorIn 
     * @param {*} point 
     */
    var movePointByVector = (vectorIn, point, distance) => {
        var vectorMagnitude = Math.sqrt(Math.pow(vectorIn.x, 2) + Math.pow(vectorIn.y, 2))

        var unitVector = {};
        unitVector.x = vectorIn.x / vectorMagnitude;
        unitVector.y = vectorIn.y / vectorMagnitude;

        var re = { x: point.x + (unitVector.x * distance), y: point.y + (unitVector.y * distance) };

        return re;
    }

    // 1st point
    var line1Point = { x: data.xLine1Point[0], y: data.xLine1Point[1] };
    // 2nd point
    var line2Point = { x: data.xLine2Point[0], y: data.xLine2Point[1] };
    // text position
    var txtPosition = { x: data.textPosition[0], y: data.textPosition[1] };

    var rotation = data.rotation;

    var line1PointMoved, line2PointMoved, p2pNormal;// 

    // 标尺线两端点
    line1PointMoved = measurementLinePoint(line1Point, rotation, txtPosition);
    line2PointMoved = measurementLinePoint(line2Point, rotation, txtPosition);
    p2pNormal = { x: (rotation == 0 ? 0 : 1), y: (rotation == 0 ? 1 : 0) };

    // 边界线 端点 edgeLinePoint1
    var edgeLine1Point1 = movePointByVector(p2pNormal, line1Point, data.dimExo);
    var edgeLine2Point1 = movePointByVector(p2pNormal, line2Point, data.dimExo);

    // 边界线 端点 edgeLinePoint2
    var edgeLine1Point2 = movePointByVector(p2pNormal, line1PointMoved, data.dimExe);
    var edgeLine2Point2 = movePointByVector(p2pNormal, line2PointMoved, data.dimExe);

    var subGeometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });

    var subNode = new ZW.Mesh(subGeometry, material);
    presentNode.add(subNode);

    // 尺寸线
    var signLineData = {};
    signLineData.startPos = [line1PointMoved.x, line1PointMoved.y, 0];
    signLineData.endPos = [line2PointMoved.x, line2PointMoved.y, 0];
    signLineData.color = data.dimClrd;
    DrawDashStraightLineSegments(signLineData, subNode);

    // 边界线
    var edgeLineData1 = {};
    edgeLineData1.startPos = [edgeLine1Point1.x, edgeLine1Point1.y, 0];
    edgeLineData1.endPos = [edgeLine1Point2.x, edgeLine1Point2.y, 0];
    edgeLineData1.color = data.dimClre;
    DrawDashStraightLineSegments(edgeLineData1, subNode);

    // 边界线
    var edgeLineData2 = {};
    edgeLineData2.startPos = [edgeLine2Point1.x, edgeLine2Point1.y, 0];
    edgeLineData2.endPos = [edgeLine2Point2.x, edgeLine2Point2.y, 0];
    edgeLineData2.color = data.dimClre;
    DrawDashStraightLineSegments(edgeLineData2, subNode);

    // 文字
    var textData = {};
    textData.textString = data.prefix + parseFloat(data.measurement).toFixed(data.dimDec) + data.suffix;
    textData.height = data.dimTxt;

    var _a = new ZW.Vector3(line1PointMoved.x - line2PointMoved.x, line1PointMoved.y - line2PointMoved.y,
        line1PointMoved.z - line2PointMoved.z);
    _b = new ZW.Vector3(1, 0, 0);

    textData.rotation = rotation;
    textData.position = data.textPosition;
    textData.color = data.dimClrt;
    textData.widthFactor = 1;
    textData.horizontalPlacement = "center";

    drawDBText(textData, subNode);

    // 箭头
    var subArrowsNode1 = new ZW.Mesh(subGeometry, material);
    subNode.add(subArrowsNode1);
    var subArrowsNode2 = new ZW.Mesh(subGeometry, material);
    subNode.add(subArrowsNode2);

    if (data.dimSah) {
        genArrowShape(data.dimBlk1Name, data.dimBlk1Shapes, subArrowsNode1, data.dimClrd);
        genArrowShape(data.dimBlk2Name, data.dimBlk2Shapes, subArrowsNode2, data.dimClrd);
    } else {
        genArrowShape(data.dimBlkName, data.dimBlkShapes, subArrowsNode1, data.dimClrd);
        genArrowShape(data.dimBlkName, data.dimBlkShapes, subArrowsNode2, data.dimClrd);
    }

    subArrowsNode1.scale.set(1 * data.dimaSz, 1 * data.dimaSz, 1 * data.dimaSz);
    subArrowsNode2.scale.set(1 * data.dimaSz, 1 * data.dimaSz, 1 * data.dimaSz);
    subArrowsNode1.position.set(line1PointMoved.x, line1PointMoved.y, 0);
    subArrowsNode2.position.set(line2PointMoved.x, line2PointMoved.y, 0);


    var tempArrowRotation = _b.angleTo(_a);
    var resArrowRotate = tempArrowRotation;
    if (_a.x < 0 && _a.y < 0)
        resArrowRotate = 0 - tempArrowRotation;
    else if (_a.x > 0 && _a.y > 0)
        resArrowRotate = tempArrowRotation;
    // else if (_a.x < 0 && _a.y > 0)
    //     resArrowRotate = 0 - (Math.PI - tempArrowRotation);
    else if (_a.x > 0 && _a.y < 0)
        resArrowRotate = 0 - tempArrowRotation;

    subArrowsNode1.rotateZ(resArrowRotate);
    subArrowsNode2.rotateZ(Math.PI + resArrowRotate);
}

/**
 * 角度标注
 * @param {*} data 
 * @param {*} presentNode   LineAngularDimension
 */
function drawLineAngularDimension(data, presentNode) {

    /**
     * 计算直线的法向量
     * @param {*} point1 直线端点1
     * @param {*} point2 直线端点2
     */
    var lineNormal = (point1, point2) => {
        var nx = point2.y - point1.y,
            ny = point1.x - point2.x;
        var normalLine = { x: nx, y: ny };
        return normalLine;
    }

    var genArrowShape = (dimBlkName, dimBlkData, arrowsNode, arrowsColor) => {
        if (dimBlkName != 'default') {
            resolveLocalData(dimBlkData, arrowsNode);
        } else {
            $(document).ready(function () {
                $.ajax({
                    url: '../default-arrow-shape.json',
                    async: true,
                    success: function (data) {
                        var arrowData = JSON.parse(data);
                        for (let i = 0; i < arrowData.length; i++) {
                            arrowData[i].color = arrowsColor;
                        }
                        resolveLocalData(arrowData, arrowsNode);
                    }
                });
            });
        }
        return arrowsNode;
    }

    /**
     * point 在方向上移动
     * @param {*} vectorIn 
     * @param {*} point 
     */
    var movePointByVector = (vectorIn, point, distance) => {
        var vectorMagnitude = Math.sqrt(Math.pow(vectorIn.x, 2) + Math.pow(vectorIn.y, 2))
        var unitVector = {};
        unitVector.x = vectorIn.x / vectorMagnitude;
        unitVector.y = vectorIn.y / vectorMagnitude;
        var re = { x: point.x + (unitVector.x * distance), y: point.y + (unitVector.y * distance) };
        return re;
    }
    var linesCrossPoint = (line1Start, line1End, line2Start, line2End) => {
        var k0 = (line1End.y - line1Start.y) / (line1End.x - line1Start.x)
        //  console.log(k0)
        var e = (line1End.y - k0 * line1End.x)
        //  console.log(e)
        var k1 = (line2End.y - line2Start.y) / (line2End.x - line2Start.x)
        //  console.log(k1)
        var e1 = (line2End.y - k1 * line2End.x)
        //  console.log(e1)
        var x = (e1 - e) / (k0 - k1)
        var y = k0 * x + e

        return { x: (e1 - e) / (k0 - k1), y: k0 * x + e }
    }

    var computeAngleByVectorToX = (vector) => {
        var re = 0;
        var axisX = new ZW.Vector3(1, 0, 0);
        var _a = new ZW.Vector3(vector.x, vector.y, 0);

        var axAngle = _a.angleTo(axisX);

        if ((_a.x > 0 && _a.y > 0))
            re = axAngle > Math.PI / 2 ? Math.PI - axAngle : axAngle;
        else if (_a.x < 0 && _a.y > 0)
            re = axAngle < Math.PI / 2 ? Math.PI - axAngle : axAngle;
        else if (_a.x < 0 && _a.y < 0)
            re = axAngle > Math.PI / 2 ? Math.PI - axAngle : axAngle;
        else if (_a.x > 0 && _a.y < 0)
            re = axAngle < Math.PI / 2 ? Math.PI - axAngle : axAngle;

        else
            re = axAngle;

        return re;
    }

    // 1st line start
    var xLine1Start = { x: data.xLine1Start[0], y: data.xLine1Start[1] };
    // 1st line end
    var xLine1End = { x: data.xLine1End[0], y: data.xLine1End[1] };
    // 2st line start
    var xLine2Start = { x: data.xLine2Start[0], y: data.xLine2Start[1] };
    // 2st line end
    var xLine2End = { x: data.xLine2End[0], y: data.xLine2End[1] };
    // arcPoint 
    var arcPoint = { x: data.arcPoint[0], y: data.arcPoint[1] };

    var crossPoint = linesCrossPoint(xLine1Start, xLine1End, xLine2Start, xLine2End);
    var radius = Math.sqrt(Math.pow((arcPoint.x - crossPoint.x), 2) + Math.pow((arcPoint.y - crossPoint.y), 2));

    var _a = new ZW.Vector3(xLine1Start.x - xLine1End.x, xLine1Start.y - xLine1End.y, 0);
    var _b = new ZW.Vector3(xLine2Start.x - xLine2End.x, xLine2Start.y - xLine2End.y, 0);
    var _c = new ZW.Vector3(arcPoint.x - crossPoint.x, arcPoint.y - crossPoint.y, 0);

    var axAngle = computeAngleByVectorToX(_a);
    var bxAngle = computeAngleByVectorToX(_b);
    var cxAngle = computeAngleByVectorToX(_c);
    if (_c.y < 0 && _c.x < 0 && cxAngle < Math.PI / 2)
        cxAngle = Math.PI + cxAngle;
    else if (_c.y < 0 && _c.x > 0 && cxAngle < Math.PI)
        cxAngle = Math.PI + cxAngle;

    var tempLinesAngles = [axAngle, Math.PI + axAngle, bxAngle, bxAngle + Math.PI, cxAngle];
    var compare = function (x, y) {//比较函数
        if (x < y) {
            return -1;
        } else if (x > y) {
            return 1;
        } else {
            return 0;
        }
    }
    tempLinesAngles = tempLinesAngles.sort(compare)
    var edgeAngle1st, edgeAngle2nd;
    for (var i = 0; i < tempLinesAngles.length; i++) {
        if (tempLinesAngles[i] == cxAngle) {
            if (i > 0 && i < tempLinesAngles.length - 1) {
                edgeAngle1st = tempLinesAngles[i - 1];
                edgeAngle2nd = tempLinesAngles[i + 1];
            } else if (i == 0) {
                edgeAngle1st = tempLinesAngles[tempLinesAngles.length - 1];
                edgeAngle2nd = tempLinesAngles[i + 1];
            } else if (i == tempLinesAngles.length - 1) {
                edgeAngle1st = 0 - (2 * Math.PI - tempLinesAngles[tempLinesAngles.length - 2]);
                edgeAngle2nd = tempLinesAngles[0];
                // edgeAngle1st = 0 - Math.PI +  Math.PI/6;
                // edgeAngle2nd = 0 - Math.PI / 3;
            }
            break;
        }
    }

    var subGeometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });
    var subNode = new ZW.Mesh(subGeometry, material);
    presentNode.add(subNode);

    // draw圆弧
    var arcData = {};
    arcData.center = [crossPoint.x, crossPoint.y, 0];
    arcData.radius = radius;
    arcData.color = data.color;
    arcData.startAngle = edgeAngle1st;
    arcData.endAngle = edgeAngle2nd;
    arcData.totalAngle = edgeAngle2nd - edgeAngle1st;
    if (Math.abs(arcData.totalAngle) > Math.PI)
        arcData.totalAngle = 2 * Math.PI - Math.abs(arcData.totalAngle);

    drawArc(arcData, presentNode);

    // 标尺线两端点
    var line1PointMoved = {}, line2PointMoved = {};

    line1PointMoved.x = Math.cos(edgeAngle1st) * radius + crossPoint.x;
    line1PointMoved.y = Math.sin(edgeAngle1st) * radius + crossPoint.y;

    line2PointMoved.x = Math.cos(edgeAngle2nd) * radius + crossPoint.x;
    line2PointMoved.y = Math.sin(edgeAngle2nd) * radius + crossPoint.y;

    // 箭头
    var subArrowsNode1 = new ZW.Mesh(subGeometry, material);
    subNode.add(subArrowsNode1);
    var subArrowsNode2 = new ZW.Mesh(subGeometry, material);
    subNode.add(subArrowsNode2);

    if (data.dimSah) {
        genArrowShape(data.dimBlk1Name, data.dimBlk1Shapes, subArrowsNode1, data.dimClrd);
        genArrowShape(data.dimBlk2Name, data.dimBlk2Shapes, subArrowsNode2, data.dimClrd);
    } else {
        genArrowShape(data.dimBlkName, data.dimBlkShapes, subArrowsNode1, data.dimClrd);
        genArrowShape(data.dimBlkName, data.dimBlkShapes, subArrowsNode2, data.dimClrd);
    }

    subArrowsNode1.scale.set(2 * data.dimaSz, 2 * data.dimaSz, 2 * data.dimaSz);
    subArrowsNode2.scale.set(1 * data.dimaSz, 1 * data.dimaSz, 1 * data.dimaSz);
    subArrowsNode1.position.set(line1PointMoved.x, line1PointMoved.y, 0);
    subArrowsNode2.position.set(line2PointMoved.x, line2PointMoved.y, 0);

    var line1Normal = lineNormal(crossPoint, line1PointMoved);
    var line2Normal = lineNormal(crossPoint, line2PointMoved);
    var line1NormalVector = new ZW.Vector3(line1Normal.x, line1Normal.y, 0);
    var line2NormalVector = new ZW.Vector3(line2Normal.x, line2Normal.y, 0);
    var axisX = new ZW.Vector3(1, 0, 0);
    var tempArrowRotation1 = line1NormalVector.angleTo(axisX);
    var tempArrowRotation2 = line2NormalVector.angleTo(axisX);

    subArrowsNode1.rotateZ(tempArrowRotation1);
    subArrowsNode2.rotateZ(tempArrowRotation2 + Math.PI);

    // 边界线 端点 edgeLinePoint1
    var p2pNormal1 = { x: line1PointMoved.x - crossPoint.x, y: line1PointMoved.y - crossPoint.y };
    var p2pNormal2 = { x: line2PointMoved.x - crossPoint.x, y: line2PointMoved.y - crossPoint.y };

    var edgeLine1Point1 = movePointByVector(p2pNormal1, crossPoint, data.dimExo);
    var edgeLine2Point1 = movePointByVector(p2pNormal2, crossPoint, data.dimExo);

    // 边界线 端点 edgeLinePoint2
    var edgeLine1Point2 = movePointByVector(p2pNormal1, line1PointMoved, data.dimExe);
    var edgeLine2Point2 = movePointByVector(p2pNormal2, line2PointMoved, data.dimExe);

    // 边界线
    var edgeLineData1 = {};
    edgeLineData1.startPos = [edgeLine1Point1.x, edgeLine1Point1.y, 0];
    edgeLineData1.endPos = [edgeLine1Point2.x, edgeLine1Point2.y, 0];
    edgeLineData1.color = data.dimClre;
    DrawDashStraightLineSegments(edgeLineData1, subNode);

    // 边界线
    var edgeLineData2 = {};
    edgeLineData2.startPos = [edgeLine2Point1.x, edgeLine2Point1.y, 0];
    edgeLineData2.endPos = [edgeLine2Point2.x, edgeLine2Point2.y, 0];
    edgeLineData2.color = data.dimClre;
    DrawDashStraightLineSegments(edgeLineData2, subNode);

}


/**
 * 填充绘制
 */
function drawHatch(data, presentNode) {
    //if(data.patternName == 'ANSI31'){
    if (data.hatchType == 'line') {
        //var centerPos = new ZW.Vector3((data.boundArray[0]+data.boundArray[3])/2.0,(data.boundArray[1]+data.boundArray[4])/2.0,(data.boundArray[2]+data.boundArray[5])/2.0);
        var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`;

        var color = colorHex(sRgb);

        var material2 = new ZW.LineBasicMaterial({
            color: color
        });

        var polyArray = data.polyArray;

        var vertices = getHatchPoint(polyArray);

        var ageo2 = new ZW.BufferGeometry();
        ageo2.addAttribute('position', new ZW.Float32BufferAttribute(vertices, 3));  //顶点的位置

        var myobj2 = new ZW.LineSegments(ageo2, material2);
        presentNode.add(myobj2);
    } else if (data.hatchType == 'circular') {

        var geometry = new ZW.CircleGeometry(data.radius, 48);

        var polyArray = [];

        for (var i = 1; i < geometry.vertices.length; i++) {
            polyArray.push(geometry.vertices[i].x + data.centerPos[0]);
            polyArray.push(geometry.vertices[i].y + data.centerPos[1]);
        }

        polyArray.push(polyArray[0]);
        polyArray.push(polyArray[1]);

        var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`;

        var color = colorHex(sRgb);

        var material2 = new ZW.LineBasicMaterial({
            color: color
        });

        var vertices = getHatchPoint(polyArray);

        var ageo2 = new ZW.BufferGeometry();
        ageo2.addAttribute('position', new ZW.Float32BufferAttribute(vertices, 3));  //顶点的位置

        var myobj2 = new ZW.LineSegments(ageo2, material2);
        presentNode.add(myobj2);

    } else if (data.hatchType == 'elliptical') {

        var curve = new ZW.EllipseCurve(
            0, 0,            // ax, aY
            data.majorRadius, data.minorRadius,           // xRadius, yRadius
            0, 2 * Math.PI,  // aStartAngle, aEndAngle
            false,            // aClockwise
            0                 // aRotation
        );

        var points = curve.getPoints(48);
        var polyArray = [];

        for (var i = 0; i < points.length; i++) {
            polyArray.push(points[i].x + data.centerPos[0]);
            polyArray.push(points[i].y + data.centerPos[1]);
        }

        polyArray.push(polyArray[0]);
        polyArray.push(polyArray[1]);

        var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`;

        var color = colorHex(sRgb);

        var material2 = new ZW.LineBasicMaterial({
            color: color
        });

        var vertices = getHatchPoint(polyArray);

        var ageo2 = new ZW.BufferGeometry();
        ageo2.addAttribute('position', new ZW.Float32BufferAttribute(vertices, 3));  //顶点的位置

        var myobj2 = new ZW.LineSegments(ageo2, material2);
        presentNode.add(myobj2);
    }
}

//通过多边形的点集来获取填充点集
function getHatchPoint(polyArray) {
    var edgeArray = []; //边界数组

    for (var i = 0; i < polyArray.length / 2 - 1; i++) {
        edgeArray.push({ x: polyArray[i * 2], y: polyArray[i * 2 + 1] });
        edgeArray.push({ x: polyArray[i * 2 + 2], y: polyArray[i * 2 + 1 + 2] });
    }
    var firstPoint = { x: polyArray[0], y: polyArray[1] };
    var lineArray = []; //线数组
    var lineAngle = Math.PI / 4;  //填充角度
    var lineLength = 5000;  //线长
    var lineDis = 40;//斜线距离

    //右移逻辑
    for (var i = 0; i < 1000; i++) {

        var p1 = { x: firstPoint.x + i * lineDis + lineLength * Math.sin(lineAngle), y: firstPoint.y + lineLength * Math.cos(lineAngle) };
        var p2 = { x: firstPoint.x + i * lineDis - lineLength * Math.sin(lineAngle), y: firstPoint.y - lineLength * Math.cos(lineAngle) };
        if (i == 0) p1 = edgeArray[0];
        var resultPoint = [];
        var mycout = 0;
        for (var j = 0; j < edgeArray.length / 2; j++) {
            var result = segmentsIntr(p1, p2, edgeArray[j * 2], edgeArray[j * 2 + 1]);
            if (result) {
                var bSamePoint = false;
                if (resultPoint.length == 1) {
                    var disX = resultPoint[0].x - result.x;
                    var disY = resultPoint[0].y - result.y;
                    if (Math.sqrt(disX * disX + disY * disY) < 1) {
                        bSamePoint = true;
                    }
                }
                if (!bSamePoint) {
                    resultPoint.push(result);
                    mycout++;
                }

            }
            if (mycout == 2) break;
        }
        if (resultPoint.length == 2) {
            lineArray.push(resultPoint[0]);
            lineArray.push(resultPoint[1]);
        }
        if (resultPoint.length == 0) {
            break;
        }
    }
    //左移逻辑
    for (var i = 1; i < 1000; i++) {
        var p1 = { x: firstPoint.x - i * lineDis + lineLength * Math.sin(lineAngle), y: firstPoint.y + lineLength * Math.cos(lineAngle) };
        var p2 = { x: firstPoint.x - i * lineDis - lineLength * Math.sin(lineAngle), y: firstPoint.y - lineLength * Math.cos(lineAngle) };
        var resultPoint = [];
        var mycout = 0;
        for (var j = 0; j < edgeArray.length / 2; j++) {
            var result = segmentsIntr(p1, p2, edgeArray[j * 2], edgeArray[j * 2 + 1]);
            if (result) {
                var bSamePoint = false;
                if (resultPoint.length == 1) {
                    var disX = resultPoint[0].x - result.x;
                    var disY = resultPoint[0].y - result.y;
                    if (Math.sqrt(disX * disX + disY * disY) < 1) {
                        bSamePoint = true;
                    }
                }
                if (!bSamePoint) {
                    resultPoint.push(result);
                    mycout++;
                }
            }
            if (mycout == 2) break;
        }
        if (resultPoint.length == 2) {
            lineArray.push(resultPoint[0]);
            lineArray.push(resultPoint[1]);
        }
        if (resultPoint.length == 0) {
            break;
        }
    }

    var vertices2 = new Float32Array(lineArray.length * 3);
    for (var i = 0; i < lineArray.length; i++) {
        vertices2[i * 3] = lineArray[i].x;
        vertices2[i * 3 + 1] = lineArray[i].y;
        vertices2[i * 3 + 2] = -0.1;
    }
    return vertices2;
}

function drawSolid(data, presentNode) {
    // var squareShape = new THREE.Shape()
    // .moveTo( 0, 0 )
    // .lineTo( 0, sqLength )
    // .lineTo( sqLength, sqLength )
    // .lineTo( sqLength, 0 )
    // .lineTo( 0, 0 );

    // 颜色
    var sRgb = `RGB(${data.color[0]}, ${data.color[1]}, ${data.color[2]})`
    var color = colorHex(sRgb);

    var orivinPoints = data.vertices;
    var squareShape = new ZW.Shape();
    squareShape.moveTo(0, 0)
    squareShape.lineTo(orivinPoints[1][0] - orivinPoints[0][0], orivinPoints[1][1] - orivinPoints[0][1])
    squareShape.lineTo(orivinPoints[3][0] - orivinPoints[0][0], orivinPoints[3][1] - orivinPoints[0][1])
    squareShape.lineTo(orivinPoints[2][0] - orivinPoints[0][0], orivinPoints[2][1] - orivinPoints[0][1])
    squareShape.lineTo(0, 0);



    var geometry = new ZW.ShapeBufferGeometry(squareShape);

    var mesh = new ZW.Mesh(geometry, new ZW.MeshBasicMaterial({ color: color }));
    mesh.position.set(orivinPoints[0][0], orivinPoints[0][1], orivinPoints[0][2]);
    mesh.scale.set(1, 1, 1);
    presentNode.add(mesh);

}

function drawMline(data, presentNode) {
    /**
     * 计算直线的法向量
     * @param {*} point1 直线端点1
     * @param {*} point1 直线端点2
     */
    var lineNormal = (point1, point2) => {
        var nx = point2.y - point1.y,
            ny = point1.x - point2.x;
        var normalLine = { x: nx, y: ny };
        return normalLine;
    }

    var subGeometry = new ZW.Geometry();
    var material = new ZW.MeshBasicMaterial({
        color: 0xff0000
    });

    var subNode = new ZW.Mesh(subGeometry, material);
    presentNode.add(subNode);

    for(var i = 0 ; i < data.vertices.length ; i++) {
        if(i >= data.vertices.length - 1)
            break;
        
        var startVerticePos = { x: data.vertices[i][0], y: data.vertices[i][1] };
        var endVerticePos = { x: data.vertices[i+1][0], y: data.vertices[i+1][1] };
         var lineVector = new ZW.Vector3(endVerticePos.x - startVerticePos.x, 
            endVerticePos.y - startVerticePos.y, endVerticePos.z - startVerticePos.z);
        var lineNormalVector = lineNormal(startVerticePos , endVerticePos);

        


    }
    
}

function drawMleader(data, presentNode) {
    
}

/**
 * string rgb change to 0x
 * @param {*} color 
 */
function colorHex(color) {
    var that = color;
    //十六进制颜色值的正则表达式
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 如果是rgb颜色表示
    if (/^(rgb|RGB)/.test(that)) {
        var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
        var strHex = "#";
        for (var i = 0; i < aColor.length; i++) {
            var hex = Number(aColor[i]).toString(16);
            if (hex.length < 2) {
                hex = '0' + hex;
            }
            strHex += hex;
        }
        if (strHex.length !== 7) {
            strHex = that;
        }
        return strHex;
    } else if (reg.test(that)) {
        var aNum = that.replace(/#/, "").split("");
        if (aNum.length === 6) {
            return that;
        } else if (aNum.length === 3) {
            var numHex = "#";
            for (var i = 0; i < aNum.length; i += 1) {
                numHex += (aNum[i] + aNum[i]);
            }
            return numHex;
        }
    }
    return that;
};

function getJiaoDian(p1, p2, p3) {
    var P = {};

    //如果p1.x==p2.x 说明是条竖着的线
    if (p1.x - p2.x == 0) {
        P.x = p1.x;
        P.y = p3.y;
    }
    else {
        var A = (p1.y - p2.y) / (p1.x - p2.x)
        var B = p1.y - A * p1.x
        var m = p3.x + A * p3.y

        P.x = (m - A * B) / (A * A + 1)
        P.y = A * P.x + B
    }

    return P
}

function GetDisByPointAndLine(p1, p2, p3) {
    var len;

    //如果p1.x==p2.x 说明是条竖着的线
    if (p1.x - p2.x == 0) {
        len = Math.abs(p3.x - p1.x)
    }
    else {
        var A = (p1.y - p2.y) / (p1.x - p2.x)
        var B = p1.y - A * p1.x

        len = Math.abs((A * p3.x + B - p3.y) / Math.sqrt(A * A + 1))
    }

    return len;
}

//计算两条线段的交点(平行或共线视作不相交)
function segmentsIntr(a, b, c, d) {

    /** 1 解线性方程组, 求线段交点. **/
    // 如果分母为0 则平行或共线, 不相交  
    var denominator = (b.y - a.y) * (d.x - c.x) - (a.x - b.x) * (c.y - d.y);
    if (denominator == 0) {
        return false;
    }

    // 线段所在直线的交点坐标 (x , y)      
    var x = ((b.x - a.x) * (d.x - c.x) * (c.y - a.y)
        + (b.y - a.y) * (d.x - c.x) * a.x
        - (d.y - c.y) * (b.x - a.x) * c.x) / denominator;
    var y = -((b.y - a.y) * (d.y - c.y) * (c.x - a.x)
        + (b.x - a.x) * (d.y - c.y) * a.y
        - (d.x - c.x) * (b.y - a.y) * c.y) / denominator;

    /** 2 判断交点是否在两条线段上 **/
    if (
        // 交点在线段1上  
        (x - a.x) * (x - b.x) <= 0 && (y - a.y) * (y - b.y) <= 0
        // 且交点也在线段2上  
        && (x - c.x) * (x - d.x) <= 0 && (y - c.y) * (y - d.y) <= 0
    ) {

        // 返回交点p  
        return {
            x: x,
            y: y
        }
    }
    //否则不相交  
    return false
}

//通过鼠标坐标来计算世界坐标
function GetWorldPosByMousePos(mousePos) {

    if (!ZW_Plane) return [0, 0];
    var mouse = new ZW.Vector2();

    mouse.x = ((mousePos[0] - ZW_renderer.domElement.getBoundingClientRect().left) / ZW_renderer.domElement.offsetWidth) * 2 - 1;
    mouse.y = -((mousePos[1] - ZW_renderer.domElement.getBoundingClientRect().top) / ZW_renderer.domElement.offsetHeight) * 2 + 1;

    ZW_raycaster.setFromCamera(mouse, ZW_activeCamera);
    var interArray = [];
    interArray.push(ZW_Plane);
    var intersects = ZW_raycaster.intersectObjects(interArray, true);
    if (intersects.length > 0) {
        return [intersects[0].point.x, intersects[0].point.y];
    }
}

//通过世界坐标来获取鼠标坐标
function GetMousePosByWorldPos(worldPos) {

    var planeGeometry = new ZW.PlaneGeometry(1, 1);
    var planeMaterial = new ZW.MeshBasicMaterial();
    var plane = new ZW.Mesh(planeGeometry, planeMaterial);
    plane.position.x = worldPos[0];
    plane.position.y = worldPos[1];
    plane.position.z = 0;
    ZW_SceneParent.add(plane);

    var vector = new ZW.Vector3();
    var viewMatrix = new ZW.Matrix4();
    var viewProjectionMatrix = new ZW.Matrix4();

    ZW_Scene.updateMatrixWorld();

    if (ZW_activeCamera.parent === null) ZW_activeCamera.updateMatrixWorld();

    viewMatrix.copy(ZW_activeCamera.matrixWorldInverse);
    viewProjectionMatrix.multiplyMatrices(ZW_activeCamera.projectionMatrix, viewMatrix);

    vector.setFromMatrixPosition(plane.matrixWorld);
    vector.applyMatrix4(viewProjectionMatrix);

    ZW_SceneParent.remove(plane);

    if (vector.z > 1.0) return [-1000, 0];
    return [(vector.x * ZW_container.offsetWidth / 2 + ZW_container.offsetWidth / 2), (- vector.y * ZW_container.offsetHeight / 2 + ZW_container.offsetHeight / 2)];
}

//获取当前视点
function GetView() {
    var cameraData = ZW_activeCamera.position.x + ',' + ZW_activeCamera.position.y + ',' + ZW_activeCamera.zoom;
    return cameraData;
}

//设置视点
function SetView(viewStr) {
    var viewArray = new Array();
    viewArray = viewStr.toString().split(",");

    var xValue = parseFloat(viewArray[0]);
    var yValue = parseFloat(viewArray[1]);
    var zoomValue = parseFloat(viewArray[2]);

    ZW_activeCamera.position.x = xValue;
    ZW_activeCamera.position.y = yValue;

    ZW_activeCamera.zoom = zoomValue;

    ZW_activeCamera.updateProjectionMatrix();

    ShowProcess();
}

function OnDrawingLoaded() {

};

function OnMouseMove(position) {

};

function OnHtmlUpdate() {

};

function OnMouseClick(position) {

};